package main

import (
	"encoding/json"
	"fmt"
	"github.com/go-redis/redis/v8"
	"net"
	"proto"
	"sync"
)
var userConn sync.Map
var connUser sync.Map
func jsonHandle(conn net.Conn,bytes []byte)error{
	cmd:=proto.Cmd{}
	fmt.Println(string(bytes))

	err:=json.Unmarshal(bytes,&cmd)
	if err != nil {
		return err
	}

	switch cmd.Cmd {
	case "Msg":
		msg:=proto.Msg{}
		err:=json.Unmarshal(bytes,&msg)
		if err != nil {
			resHandle(conn,1,"msg协议错误")
		}

		from,b :=connUser.Load(conn)
		if !b {
			resHandle(conn,1,"未登录")
		}
		msg.From=from.(string)

		id,err:=rdb.HGet(ctx,redisPrefix+"Id",msg.To).Result()
		if err != redis.Nil {
			resHandle(conn,1,"对象不存在")
		}
		toConn,b :=userConn.Load(id)
		if b {
			resHandle(conn,1,"对象不存在")
		}
		toConnect,_:=toConn.(net.Conn)
		msgHandle(toConnect,&msg)

	case "LoginCmd":
		msg:=proto.LoginCmd{}
		err:=json.Unmarshal(bytes,&msg)
		if err != nil {
			return err
		}
		id,err:=LoginCmdHandle(&msg)
		if err!=nil {
			resHandle(conn,1,"登录失败"+fmt.Sprintf("%v",err))
		}else{
			userConn.Store(id,conn)
			connUser.Store(conn,id)
			resHandle(conn,0,"登录成功")
		}

	case "RegCmd":
		msg:=proto.RegCmd{}
		err:=json.Unmarshal(bytes,&msg)
		if err != nil {
			return err
		}
		bool:=RegCmdHandle(&msg)
		if bool {
			resHandle(conn,0,"注册成功")
		}else{
			resHandle(conn,1,"注册失败")
		}
	case "UserList":

		UserInfos,err:=UserListHandle(conn)
		if err!=nil {
			return err
		}
		//fmt.Println(UserInfos)
		//return nil
		ulr := proto.UserListRes{}
		ulr.Cmd.Cmd="UserListRes"
		ulr.Code=0
		ulr.Error=""
		ulr.List=*UserInfos
		bytes,_:=json.Marshal(ulr)
		replyHandle(conn,bytes)
	default:
		fmt.Println("协议错误",cmd.Cmd)
	}
	return nil
}

func RegCmdHandle(regCmd *proto.RegCmd) bool {
	user:=User{}
	err:=user.CreateUserStr(regCmd.NickName,regCmd.Password,regCmd.Sex)
	if err!=nil {
		fmt.Println(err)
		return false
	}
	return true
}

func LoginCmdHandle(cmd *proto.LoginCmd)(string,error)  {
	user:=User{}
	user.NickName=cmd.NickName
	user.Password=cmd.Password
	return user.login()
}
func msgHandle(conn net.Conn,cmd *proto.Msg) {
	bytes,_:=json.Marshal(cmd)
	replyHandle(conn,bytes)
}

func resHandle(conn net.Conn,code int,err string) {
	res:=proto.Res{}
	res.Cmd.Cmd="Res"
	res.Code=code
	res.Error=err
	bytes,_:=json.Marshal(res)
	replyHandle(conn,bytes)
}
func UserListHandle(conn net.Conn)(*[]proto.UserInfo,error){
	return AllList()
}


